#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        if (nums.size() < 4)
            return ret;
        for (int i = 0; i < nums.size() - 3; ++i)
        {
            long long target1 = target - nums[i];
            for (int j = i + 1; j < nums.size() - 2; ++j)
            {
                long long target2 = target1 - nums[j];
                int left = j + 1, right = nums.size() - 1;
                while (left < right)
                {
                    int l = nums[left], r = nums[right];
                    if (l + r > target2)
                    {
                        while (left < right && nums[right] == nums[right - 1]) --right;
                        --right;
                    }
                    else if (l + r < target2)
                    {
                        while (left < right && nums[left] == nums[left + 1]) ++left;
                        ++left;
                    }
                    else
                    {
                        vector<int> v{ nums[i],nums[j],l,r };
                        ret.push_back(v);
                        while (left < right && nums[right] == nums[right - 1]) --right;
                        while (left < right && nums[left] == nums[left + 1]) ++left;
                        --right;
                        ++left;
                    }
                }
                while (j < nums.size() - 2 && nums[j] == nums[j + 1]) ++j;
            }
            while (i < nums.size() - 3 && nums[i] == nums[i + 1]) ++i;
        }
        return ret;
    }
};